package com.qkl.qkl.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qkl.qkl.common.Dto;
import com.qkl.qkl.common.Dtos;
import com.qkl.qkl.service.DamAssetService;
import com.qkl.qkl.service.ISSService;
import com.qkl.qkl.service.UserService;
import com.qkl.qkl.util.Conts;
import com.qkl.qkl.util.DateUtil;
import com.tencent.trustsql.sdk.TrustSDK;
import com.tencent.trustsql.sdk.bean.PairKey;
import com.tencent.trustsql.sdk.exception.TrustSDKException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by with Intellij IDEA
 * Author : tianhaoyi
 * Date : 2018/7/20
 * Time : 9:22
 */
@RestController
public class APIController {

    //身份管理
    @Autowired
    UserService userService;
    //信息共享
    @Autowired
    ISSService issService;
    //资产发行
    @Autowired
    DamAssetService damAssetService;

    /**
     * ********************************身份管理**************************************************
     */
    /**
     * 注册用户
     * @return
     */
    @RequestMapping(value = "user_cert/register")
    public String registerUser(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
//        dto.put("mch_id", "gb2af850d5722c68");
//        dto.put("product_code","productA");
//        dto.put("seq_no",RequestDataUtil.getUUID());
//        dto.put("user_id","123");
//        dto.put("user_fullName","嘿哈");

        return userService.userRegiest(dto);
    }

    /**
     * 获取用户信息
     * @return
     */
    @RequestMapping(value = "user_cert/fetch")
    public String getUserInfo(HttpServletRequest request) throws Exception{
        Dto dto = Dtos.newDto(request);
        return userService.getUserInfo(dto);
    }

    /**
     * 创建用户账户
     * @return
     */
    @RequestMapping(value = "account_cert/register")
    public String createUserAccount(HttpServletRequest request) throws Exception{
        Dto dto = Dtos.newDto(request);
        return userService.createUserAccount(dto);
    }

    /**
     * 获取用户的账户地址列表
     * @return
     */
    @RequestMapping(value = "account_cert/fetch_list")
    public String getUserAccountList(HttpServletRequest request) throws Exception{
        Dto dto = Dtos.newDto(request);
        return userService.getUserAccountList(dto);
    }

    /**
     * 获取用户的账户公钥
     * @return
     */
    @RequestMapping(value = "account_cert/fetch")
    public String getUserAccountPubKey(HttpServletRequest request) throws Exception{
        Dto dto = Dtos.newDto(request);
        return userService.getUserAccountPubKey(dto);
    }

    /**
     * ********************************信息共享**************************************************
     */
    /**
     * 共享信息新增/追加
     */
    @RequestMapping(value = "trustsql_iss_append_v1")
    public String issAppend(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);

        JSONObject jsonObject = new JSONObject();

//        dto.put("mch_id","gb2af850d5722c68");
////        dto.put("node_id","nd8e77dwnwmauq8gxr");
////        dto.put("chain_id","chv3tnv35nave3kajg");
////        dto.put("ledger_id","ld9ijtgccyfphvugmj");
////        dto.put("info_key","313121323122333");
////        dto.put("info_version",1);
////        dto.put("state",0);
////        dto.put("content","{\"name\":\"tianhaoyi\",\"age\":\"23\"}");
////        dto.put("notes","{\"name\":\"huhahei\",\"age\":\"23\"}");

        jsonObject.put("version",Conts.VERSION);
        jsonObject.put("sign_type",Conts.SIGN_TYPE);
        jsonObject.put("node_id",dto.getString("node_id"));
        jsonObject.put("chain_id",dto.getString("chain_id"));
        jsonObject.put("ledger_id",dto.getString("ledger_id"));
        jsonObject.put("info_key",dto.getString("info_key"));
        jsonObject.put("info_version",dto.getString("info_version"));
        jsonObject.put("state",dto.getString("state"));

        jsonObject.put("content",JSONObject.parseObject(dto.getString("content")));

        jsonObject.put("notes",JSONObject.parseObject(dto.getString("notes")));

        jsonObject.put("commit_time",DateUtil.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
        jsonObject.put("timestamp",System.currentTimeMillis()/1000);

        dto.put("jsonObject",jsonObject.toString());

        String result = issService.issAppend(dto);

        return result;
    }


    /**
     * 共享信息查询
     */
    @RequestMapping(value = "trustsql_iss_query_v1")
    public String issQuery(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);

//        dto.put("mch_id","gb2af850d5722c68");
//        dto.put("prvKey","2r5KM0GFlyVJaZzyDVh2fCzwNykyjINJDTUFQKgMStw=");
//        dto.put("chain_id","ch_tencent_test");
//        dto.put("ledger_id","ld_tencent_iss");
//        dto.put("node_id","nd8e77dwnwmauq8gxr");
//        dto.put("chain_id","chv3tnv35nave3kajg");
//        dto.put("ledger_id","ld9ijtgccyfphvugmj");


        JSONObject jsonObject = new JSONObject();

        jsonObject.put("version",Conts.VERSION);
        jsonObject.put("sign_type",Conts.SIGN_TYPE);
        jsonObject.put("chain_id",dto.getString("chain_id"));
        jsonObject.put("ledger_id",dto.getString("ledger_id"));
        jsonObject.put("timestamp",System.currentTimeMillis()/1000);

        if(dto.containsKey("node_id")){
            jsonObject.put("node_id",dto.getString("node_id"));
        }
        if(dto.containsKey("info_key")){
            jsonObject.put("info_key",dto.getString("info_key"));
        }
        if(dto.containsKey("info_version")){
            jsonObject.put("info_version",dto.getString("info_version"));
        }
        if(dto.containsKey("state")){
            jsonObject.put("state",dto.getString("state"));
        }
        if(dto.containsKey("content")){
            jsonObject.put("content",JSONObject.parseObject(dto.getString("content")));
        }
        if(dto.containsKey("notes")){
            jsonObject.put("notes",JSONObject.parseObject(dto.getString("notes")));
        }
        if(dto.containsKey("range")){
            jsonObject.put("range",JSONObject.parseObject(dto.getString("range")));
        }
        if(dto.containsKey("account")){
            jsonObject.put("account",dto.getString("account"));
        }
        if(dto.containsKey("t_hash")){
            jsonObject.put("t_hash",dto.getString("t_hash"));
        }
        if(dto.containsKey("page_no")){
            jsonObject.put("page_no",dto.getString("page_no"));
        }
        if(dto.containsKey("page_limit")){
            jsonObject.put("page_limit",dto.getString("page_limit"));
        }
        dto.put("jsonObject",jsonObject);
        return issService.issQuery(dto);
    }

    /**
     * ********************************数字资产**************************************************
     */
    /**
     * 资产发行申请
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_issue_apply_v1")
    public  String damAssetApply(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetApply(dto);
    }
    /**
     * 资产发行提交
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_issue_submit_v1")
    public  String damAssetSubmit(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetSubmit(dto);
    }
    /**
     * 资产转让至中间账户申请（转让签收场景）
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_transfer_mid_apply_v1")
    public  String damAssetTransferMidApplay(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetTransferMidApplay(dto);
    }
    /**
     * 资产转让至中间账户提交（转让签收场景）
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_transfer_mid_submit_v1")
    public  String damAssetTransferMidSubmit(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetTransferMidSubmit(dto);
    }
    /**
     * 资产转让签收申请（转让签收场景）
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_signin_apply_v1")
    public  String damAssetSigninApplay(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetSigninApplay(dto);
    }
    /**
     * 资产转让签收提交（转让签收场景）
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_signin_submit_v1")
    public  String damAssetSigninSubmit(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetSigninSubmit(dto);
    }
    /**
     * 资产转让申请（非签收场景）
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_transfer_apply_v1")
    public  String damAssetTransferApplay(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetTransferApplay(dto);
    }
    /**
     * 资产转让提交（非签收场景）
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_transfer_submit_v1")
    public  String damAssetTransferSubmit(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetTransferSubmit(dto);
    }
    /**
     * 资产兑付申请
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_settle_apply_v1")
    public  String damAssetSettleApply(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetSettleApply(dto);
    }
    /**
     * 资产兑付提交
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_settle_submit_v1")
    public  String damAssetSettleSubmit(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetSettleSubmit(dto);
    }
    /**
     * 资产批量查询
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_account_query_v1")
    public  String damAssetAccountQuery(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetAccountQuery(dto);
    }
    /**
     * 交易批量查询
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_trans_query_v1")
    public  String damAssetTransQuery(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetTransQuery(dto);
    }
    /**
     * 资产汇总对账
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_rec_sum_query_v1")
    public  String damAssetRecSumQuery(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetRecSumQuery(dto);
    }
    /**
     * 资产明细对账
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_rec_detail_query_v1")
    public  String damAssetRecDetailQuery(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetRecDetailQuery(dto);
    }
    /**
     * 交易汇总对账
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_rec_trans_sum_query_v1")
    public  String damAssetRecTransSumQuery(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetRecTransSumQuery(dto);
    }
    /**
     * 交易明细对账
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_rec_trans_detail_query_v1")
    public  String damAssetRecTransDetailQuery(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetRecTransDetailQuery(dto);
    }
    /**
     * 资产批量转让至中间账户申请(转让签收场景)
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_multtransmid_apply_v1")
    public  String damAssetMulttransmidApply(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetMulttransmidApply(dto);
    }
    /**
     * 资产批量转让至中间账户提交(转让签收场景)
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_multtransmid_submit_v1")
    public  String damAssetMulttransmidSubmit(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetMulttransmidSubmit(dto);
    }
    /**
     * 资产批量转让签收申请(转让签收场景)
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_multsignin_apply_v1")
    public  String damAssetMulsigninApply(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetMulsigninApply(dto);
    }
    /**
     * 资产批量转让签收提交(转让签收场景)
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "dam_asset_multsignin_submit_v1")
    public  String damAssetMulsigninSubmit(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return  damAssetService.damAssetMulsigninSubmit(dto);
    }


    /**
     * 获取公钥
     * @param request
     * @return
     */
    @RequestMapping(value = "getPairKey")
    public String getPairKey(HttpServletRequest request) throws Exception{
        PairKey pair = TrustSDK.generatePairKey(true);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("publicKey",pair.getPublicKey());
        jsonObject.put("privateKey",pair.getPrivateKey());

        return jsonObject.toJSONString();
    }

    /**
     * 通过私钥生成公钥
     * @param request
     * @return
     */
    @RequestMapping(value = "getPubKeyByPrvKey")
    public String getPubKeyByPrvKey(HttpServletRequest request) throws Exception {
        Dto dto = Dtos.newDto(request);
        return TrustSDK.generatePubkeyByPrvkey(dto.getString("prvKey"),true);
    }

    /**
     * 通过公钥生成地址
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "getAddrByPubkey")
    public String getAddrByPubkey(HttpServletRequest request) throws Exception{
        Dto dto = Dtos.newDto(request);
        return TrustSDK.generateAddrByPubkey(dto.getString("pubKey"));
    }
    /**
     * 通过私钥生成地址
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "getAddrByPrvkey")
    public String getAddrByPrvkey(HttpServletRequest request) throws Exception{
        Dto dto = Dtos.newDto(request);
        return TrustSDK.generateAddrByPrvkey(dto.getString("prvKey"));
    }
    /**
     * 验证公私钥是否匹配
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "checkPairKey")
    public String checkPairKey(HttpServletRequest request) throws Exception{
        Dto dto = Dtos.newDto(request);
        boolean isMatch = TrustSDK.checkPairKey(dto.getString("prvKey"),dto.getString("pubKey"));

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("isMatch",isMatch);

        return jsonObject.toJSONString();
    }

    /**
     * 生成签名
     * @return
     */
    @RequestMapping(value = "getSignStr")
    public  String getSignStr(HttpServletRequest request) throws Exception{
        Dto dto = Dtos.newDto(request);
        return TrustSDK.signString(dto.getString("prvKey"),dto.getString("signStr").getBytes("UTF-8"),false);
    }
}
